package lights;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import obj.Edge;
import obj.Junction;
import obj.Node;
import sim.VehicleComponent;
import sim.VehicleRunnable;
import ui.VehicleQueueReportPanel;

public class LightRunnable implements Runnable {

	private List<Junction> junctionList = new ArrayList<Junction>();
	private VehicleComponent component;
	private Set<Node> allJunctionNodes = new HashSet<Node>();
	private Map<String, List> phaseMap = new HashMap<String, List>();
	public Map<Edge, Set<String>> carsInEdgesMap = new HashMap<Edge, Set<String>>();;

	public LightRunnable(List<Junction> juncList, VehicleComponent comp, Map<Edge, Set<String>> map) {
		this.junctionList = juncList;
		this.component = comp;
		this.carsInEdgesMap = map;
		/* set all nodes in junction */
		for (Phase p : junctionList.get(0).getPhaseList()) {
			for (Node n : p.getPhaseNodes()) {
				n.setLightState(Node.STATUS_RED);
				allJunctionNodes.add(n);
			}

			/* set nodes per phase */

			phaseMap.put(p.getName(), p.getPhaseNodes());

		}

		component.addNodes(allJunctionNodes);
	}

	@Override
	public void run() {

		int count = 0;
		int lightCycle = 1;
		int start = 0;
		while (true) {

			if (count > 2) {
				count = 0;
				if (start == 0) {
					VehicleQueueReportPanel.drawTable(carsInEdgesMap);
				}
				VehicleRunnable.updateLightCycle(lightCycle);
				lightCycle++;
				start++;
			}
			List<Phase> phaseList = junctionList.get(0).getPhaseList();
			Phase currentPhase = phaseList.get(count);
			int phaseDelay = currentPhase.getGreenTime();
			addGreenNodes(phaseMap.get(currentPhase.getName()));
			count++;
			try {
				Thread.sleep(phaseDelay);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}

	}

	private void addGreenNodes(List<Node> nodes) {

		for (Node n : allJunctionNodes) {
			n.setLightState(Node.STATUS_RED);
		}

		for (Node node : nodes) {
			node.setLightState(Node.STATUS_GREEN);
		}
		component.addGreenNodes(nodes);
	}

}
